import gradio as gr
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ.get('ZhipuAI-APIKey'),
    base_url="https://open.bigmodel.cn/api/paas/v4",
)


def chat(prompt, history):
    messages = [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": prompt}
    ]
    try:
        response = client.chat.completions.create(
            model="glm-4-flash",
            messages=messages,
        )
        yield response.choices[0].message.content
    except Exception as e:
        yield str(e)


# Chat聊天窗口
app = gr.ChatInterface(fn=chat, title="Basic Chat")
app.launch(server_port=7860)
